package org.zjx.data;

import org.zjx.command.entity.screen.*;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;
import com.alibaba.fastjson2.TypeReference;
import org.zjx.command.enums.TeleportType;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

// JSON 序列化工具
public class SceneJsonSerializer {

    // 场景转JSON
    public static String sceneToJson(Scene scene) {
        Map<String, Object> sceneMap = new HashMap<>();
        sceneMap.put("name", scene.getName());

        // TabMap单独序列化
        sceneMap.put("tabMap", tabMapToJson(scene.getTabMap()));

        sceneMap.put("properties", scene.getProperties());

        // NPC列表
        List<Map<String, Object>> npcList = new ArrayList<>();
        for (Npc npc : scene.getNpcs()) {
            npcList.add(npcToMap(npc));
        }
        sceneMap.put("npcs", npcList);

        // 房间列表
        List<Map<String, Object>> roomList = new ArrayList<>();
        for (Room room : scene.getRooms()) {
            roomList.add(roomToMap(room));
        }
        sceneMap.put("rooms", roomList);

        // 传送点列表
        List<Map<String, Object>> teleportList = new ArrayList<>();
        for (Teleport tp : scene.getTeleports()) {
            teleportList.add(teleportToMap(tp));
        }
        sceneMap.put("teleports", teleportList);

        // 新增：怪物列表序列化
        List<String> monsterList = scene.getMonsters();
        if (monsterList != null && !monsterList.isEmpty()) {
            sceneMap.put("monsters", monsterList);
        }

        return JSON.toJSONString(sceneMap, JSONWriter.Feature.PrettyFormat);
    }

    // TabMap单独序列化
    public static String tabMapToJson(TabMap tabMap) {
        Map<String, Object> tabMapObj = new HashMap<>();
        tabMapObj.put("width", tabMap.width);
        tabMapObj.put("height", tabMap.height);
        return JSON.toJSONString(tabMapObj);
    }

    // 从JSON解析TabMap
    public static TabMap jsonToTabMap(String json) {
        Map<String, Object> tabMapMap = JSON.parseObject(json, new TypeReference<Map<String, Object>>() {});
        int width = ((Number) tabMapMap.get("width")).intValue();
        int height = ((Number) tabMapMap.get("height")).intValue();
        return new TabMap(width, height);
    }

    private static Map<String, Object> npcToMap(Npc npc) {
        Map<String, Object> npcMap = new HashMap<>();
        npcMap.put("sceneName", npc.sceneName); // 新增
        npcMap.put("name", npc.name);

        // 移动路径列表
        List<Map<String, Object>> movePath = new ArrayList<>();
        for (Point point : npc.movePath) {
            Map<String, Object> pointMap = new HashMap<>();
            pointMap.put("x", point.x);
            pointMap.put("y", point.y);
            movePath.add(pointMap);
        }
        npcMap.put("movePath", movePath);
        npcMap.put("functions", npc.functions);

        return npcMap;
    }

    private static Map<String, Object> roomToMap(Room room) {
        Map<String, Object> roomMap = new HashMap<>();
        roomMap.put("name", room.name);

        // 房间的TabMap也单独序列化
        if (room.tabMap != null) {
            roomMap.put("tabMap", tabMapToJson(room.tabMap));
        }

        // 图片位置信息
        List<Map<String, Object>> imageLocations = new ArrayList<>();
        for (Map.Entry<BufferedImage, Point> entry : room.imageLocations.entrySet()) {
            Map<String, Object> imageLocation = new HashMap<>();
            imageLocation.put("imageWidth", entry.getKey().getWidth());
            imageLocation.put("imageHeight", entry.getKey().getHeight());
            imageLocation.put("x", entry.getValue().x);
            imageLocation.put("y", entry.getValue().y);
            imageLocations.add(imageLocation);
        }
        roomMap.put("imageLocations", imageLocations);

        // NPC列表
        List<Map<String, Object>> npcList = new ArrayList<>();
        for (Npc npc : room.npcs) {
            npcList.add(npcToMap(npc));
        }
        roomMap.put("npcs", npcList);

        return roomMap;
    }

    private static Map<String, Object> teleportToMap(Teleport teleport) {
        Map<String, Object> tpMap = new HashMap<>();

        // 新增：fromScene字段
        tpMap.put("fromScene", teleport.fromScene);

        // from位置
        Map<String, Object> fromMap = new HashMap<>();
        fromMap.put("x", teleport.from.x);
        fromMap.put("y", teleport.from.y);
        tpMap.put("from", fromMap);

        // to位置
        Map<String, Object> toPosMap = new HashMap<>();
        toPosMap.put("x", teleport.toPos.x);
        toPosMap.put("y", teleport.toPos.y);
        tpMap.put("toPos", toPosMap);

        tpMap.put("toScene", teleport.toScene);

        // click位置（可选）
        if (teleport.clickPos != null) {
            Map<String, Object> clickPosMap = new HashMap<>();
            clickPosMap.put("x", teleport.clickPos.x);
            clickPosMap.put("y", teleport.clickPos.y);
            tpMap.put("clickPos", clickPosMap);
        }

        // NPC（可选）
        if (teleport.npc != null) {
            tpMap.put("npc", npcToMap(teleport.npc));
        }

        // 修正：枚举转字符串
        tpMap.put("type", teleport.type.name());

        return tpMap;
    }

    // JSON转场景
    public static Scene jsonToScene(String json) {
        Map<String, Object> sceneMap = JSON.parseObject(json, new TypeReference<Map<String, Object>>() {});

        String name = (String) sceneMap.get("name");

        // 解析TabMap
        String tabMapJson = (String) sceneMap.get("tabMap");
        TabMap tabMap = jsonToTabMap(tabMapJson);

        Scene scene = new Scene(name, tabMap);

        // 解析属性
        Map<String, Object> properties = safeCastToMap(sceneMap.get("properties"));
        if (properties != null) {
            scene.getProperties().putAll(properties);
        }

        // 解析NPC
        List<Map<String, Object>> npcList = safeCastToList(sceneMap.get("npcs"));
        if (npcList != null) {
            for (Map<String, Object> npcMap : npcList) {
                scene.addNpc(mapToNpc(npcMap));
            }
        }

        // 解析房间
        List<Map<String, Object>> roomList = safeCastToList(sceneMap.get("rooms"));
        if (roomList != null) {
            for (Map<String, Object> roomMap : roomList) {
                scene.addRoom(mapToRoom(roomMap));
            }
        }

        // 解析传送点
        List<Map<String, Object>> teleportList = safeCastToList(sceneMap.get("teleports"));
        if (teleportList != null) {
            for (Map<String, Object> tpMap : teleportList) {
                scene.addTeleport(mapToTeleport(tpMap));
            }
        }

        // 新增：解析怪物列表
        List<String> monsterList = safeCastToStringList(sceneMap.get("monsters"));
        if (monsterList != null) {
            for (String monster : monsterList) {
                scene.addMonster(monster);
            }
        }

        return scene;
    }

    @SuppressWarnings("unchecked")
    private static Map<String, Object> safeCastToMap(Object obj) {
        if (obj instanceof Map) {
            return (Map<String, Object>) obj;
        }
        return null;
    }

    @SuppressWarnings("unchecked")
    private static List<Map<String, Object>> safeCastToList(Object obj) {
        if (obj instanceof List) {
            return (List<Map<String, Object>>) obj;
        }
        return null;
    }

    // 新增：安全转换为字符串列表的方法
    @SuppressWarnings("unchecked")
    private static List<String> safeCastToStringList(Object obj) {
        if (obj instanceof List) {
            return (List<String>) obj;
        }
        return null;
    }

    private static Npc mapToNpc(Map<String, Object> npcMap) {
        String sceneName = (String) npcMap.get("sceneName"); // 新增
        String name = (String) npcMap.get("name");

        // 使用新的构造函数
        Npc npc = new Npc(sceneName, name);

        // 解析移动路径
        List<Map<String, Object>> movePath = safeCastToList(npcMap.get("movePath"));
        if (movePath != null) {
            for (Map<String, Object> pointMap : movePath) {
                int x = ((Number) pointMap.get("x")).intValue();
                int y = ((Number) pointMap.get("y")).intValue();
                npc.addMovePath(new Point(x, y));
            }
        }

        // 解析功能
        Map<String, List<String>> functions = safeCastToFunctionsMap(npcMap.get("functions"));
        if (functions != null) {
            npc.functions.putAll(functions);
        }

        return npc;
    }

    @SuppressWarnings("unchecked")
    private static Map<String, List<String>> safeCastToFunctionsMap(Object obj) {
        if (obj instanceof Map) {
            return (Map<String, List<String>>) obj;
        }
        return null;
    }

    private static Room mapToRoom(Map<String, Object> roomMap) {
        String name = (String) roomMap.get("name");

        // 解析房间的TabMap
        String tabMapJson = (String) roomMap.get("tabMap");
        TabMap tabMap = jsonToTabMap(tabMapJson);

        Room room = new Room(name, tabMap);

        // 解析图片位置
        List<Map<String, Object>> imageLocations = safeCastToList(roomMap.get("imageLocations"));
        if (imageLocations != null) {
            for (Map<String, Object> imageLocation : imageLocations) {
                int x = ((Number) imageLocation.get("x")).intValue();
                int y = ((Number) imageLocation.get("y")).intValue();
                int width = ((Number) imageLocation.get("imageWidth")).intValue();
                int height = ((Number) imageLocation.get("imageHeight")).intValue();

                // 创建空的BufferedImage占位
                BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
                room.addImageLocations(image, new Point(x, y));
            }
        }

        // 解析NPC
        List<Map<String, Object>> npcList = safeCastToList(roomMap.get("npcs"));
        if (npcList != null) {
            for (Map<String, Object> npcMap : npcList) {
                room.addNpc(mapToNpc(npcMap));
            }
        }

        return room;
    }

    private static Teleport mapToTeleport(Map<String, Object> tpMap) {
        // 新增：解析fromScene字段
        String fromScene = (String) tpMap.get("fromScene");

        // 解析from位置
        Map<String, Object> fromMap = safeCastToMap(tpMap.get("from"));
        Point from = new Point(
                ((Number) fromMap.get("x")).intValue(),
                ((Number) fromMap.get("y")).intValue()
        );

        // 解析to位置
        Map<String, Object> toPosMap = safeCastToMap(tpMap.get("toPos"));
        Point toPos = new Point(
                ((Number) toPosMap.get("x")).intValue(),
                ((Number) toPosMap.get("y")).intValue()
        );

        String toScene = (String) tpMap.get("toScene");

        // 修正：字符串转枚举
        String typeStr = (String) tpMap.get("type");
        TeleportType type = TeleportType.valueOf(typeStr);

        // 处理可选字段
        Point clickPos = null;
        Map<String, Object> clickPosMap = safeCastToMap(tpMap.get("clickPos"));
        if (clickPosMap != null) {
            clickPos = new Point(
                    ((Number) clickPosMap.get("x")).intValue(),
                    ((Number) clickPosMap.get("y")).intValue()
            );
        }

        Npc npc = null;
        Map<String, Object> npcMap = safeCastToMap(tpMap.get("npc"));
        if (npcMap != null) {
            npc = mapToNpc(npcMap);
        }

        // 更新构造函数调用，添加fromScene参数
        return new Teleport(fromScene, from, toScene, toPos, clickPos, npc, type);
    }
}